<?php
namespace App\Http\Services;

use App\Http\Model\EquipAuction;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Lib\Response;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class EquipService extends CommonServices
{
    protected $equipModel;//装备模型
    protected $roomModel;
    protected $model_union_user;
    protected $model_union;

    protected $auctionChatForbiddenKey = 'EQUIP:AUCTION:CHAT:FORBIDDEN:HOUR:';//公聊封禁用户小时缓存 string EQUIP:AUCTION:CHAT:FORBIDDEN:HOUR:{USERID} => 1/3
    protected $auctionChatNeverKey = 'EQUIP:AUCTION:CHAT:FORBIDDEN:NEVER';//公聊封禁用户永久缓存 set EQUIP:AUCTION:CHAT:FORBIDDEN:NEVER {user_id}

    public function __construct()
    {
        parent::__construct();
        $this->equipModel = new EquipAuction();
        $this->roomModel = new Room();
        $this->model_union_user = new UnionUser();
        $this->model_union = new Union();
    }
    
    //获取用户所持装备信息
    public function getUserEquip($user_id, $equip_type,$page,$limit){
        $res = $this->equipModel->getUserEquip($user_id,$equip_type,$page,$limit);
        return $res;
    }

    //装备拍卖上架
    public function insertSell($equipId, $user_id, $sellNums, $price, $roomId=0)
    {
        $code = Hint::SUCCESS;
        $msg = 'ok';
        $data = [];
        do{
            //判断装备信息是否存在
            $equip_info = $this->equipModel->EquipInfo($equipId);
            //查看用户出售的商品是否是从APP商店购买的
            $appShopEquipInfo = $this->equipModel->appShopEquipInfo($equipId);
            if(empty($equip_info)){
                $code = Hint::ERROR;
                $msg = '装备信息不存在';
                break;
            }
            //查看装备是否可以售卖
            if($equip_info['can_sale'] == 2 || !empty($appShopEquipInfo)){
                $code = Hint::ERROR;
                $msg = '装备不可售卖';
                break;
            }
            //判断所选的装备是否是正在装备的,若是则提示不可售卖
            $checkUsedEquip = $this->equipModel->checkEquipStatus($equipId, $user_id);
            if(!empty($checkUsedEquip))
            {
                if($checkUsedEquip['if_use'] == 1 && $checkUsedEquip['num'] == 1){
                    $code = Hint::ERROR;
                    $msg = '该装备已佩戴，请卸下装备后再上架';
                    break;
                }

                //查看售卖数量是否超过所拥有的数量
                if($checkUsedEquip['num'] < $sellNums){
                    $code = Hint::ERROR;
                    $msg = '该装备所属数量不足';
                    break;
                }
            }else{
                $code = Hint::ERROR;
                $msg = '无法出售';
                break;
            }
            //上架数据处理
            for($i=1;$i<=$sellNums;$i++){
                $datas['equip_id'] = $equipId; //装备id
                $datas['user_id'] = $user_id; //出售用户id
                $datas['room_id'] = $roomId; //房间id
                $datas['price'] = $price;//出售价格
                $datas['sale_time'] = date('Y-m-d H:i:s',time());
                $datas['sale_status'] = 1;//1=上架 2=已出售 3=用户下架 4=运营下架
                $datas['created_at'] =  date('Y-m-d H:i:s',time());
                $insertStatus = $this->equipModel->insertDatas($datas,$sellNums);
            }
            //查询目前装备数量
            $data['nums'] = $checkUsedEquip['num'] - $sellNums;
        }while(false);

        return compact('code', 'msg', 'data');
        
    }

    //拍卖下架
    public function unsaleEquip($user_id, $auctionId){
        //查看下架装备是否卖出
        $check = $this->equipModel->getEquipAuctionInfo($auctionId);
        //检查下架的装备是否是该对应用户的
        if($check['user_id'] != $user_id){
            return ['code'=>'-1','msg'=>'无权操作'];
        }
        if($check['sale_status'] == 1){
            $status = $this->equipModel->unsaleEquip($user_id, $auctionId);
            return ['code'=>1,'msg'=>'ok'];
        }else{
            return ['code'=>'-1','msg'=>'拍卖装备已售出或已下架'];
        }
    }

    //获取拍卖行列表
    public function getShopList($page, $limit, $kwd, $equip_type, $equip_level, $user_id)
    {
        //获取数据拍卖
        $data = $this->equipModel->getShopList($page, $limit, $kwd, $equip_type, $equip_level, $user_id);
        return $data;
    }

    //获取装备分类
    public function getEquipType(){
        $data = $this->equipModel->getEquipType();
        return $data;
    }

    //获取用户金豆数
    public function getUserJd($user_id=0){
        $count = $this->equipModel->getUserJd($user_id);
        return $count;
    }

    //用户购买拍卖行装备检查条件
    public function buyEquip($user_id, $buy_id){
        //查看装备出售信息是否是自己出售的,自己出售的不能购买
        $equipAuctionInfo = $this->equipModel->getEquipAuctionInfo($buy_id);
        if(empty($equipAuctionInfo)){
            return ['code'=>'-1','msg'=>'拍卖装备不存在'];
        }
        if($equipAuctionInfo['user_id'] == $user_id){
            return ['code'=>'-1','msg'=>'不能自己购买自己出售的装备'];
        }
        //购买装备是否存在不存在无法拍卖
        $equipInfo = $this->equipModel->EquipInfo($equipAuctionInfo['equip_id']);
        if(empty($equipInfo)){
            return ['code'=>'-1','msg'=>'拍卖装备不存在'];
        }
        //购买数量
        $equipAuctionInfo['num'] = 1;

        //获取登录用户的金豆数
        $jdcount = $this->equipModel->getUserJd($user_id);
        if(empty($jdcount) || $jdcount < $equipAuctionInfo['price']){
            return ['code'=>'-1','msg'=>'金豆数不足,请充值'];
        }

        //扣减金豆+发送装备数据
        $status = $this->equipModel->userByEquip($user_id,$equipAuctionInfo);
        if($status){
            return ['code'=>1,'msg'=>'ok'];
        }else{
            return ['code'=>-1,'msg'=>'请重新尝试购买'];
        }
        
    }

    //获取拍卖记录
    public function auctionRecord($user_id, $type, $page, $limit, $roomId){
        //获取拍卖记录
        $res = $this->equipModel->auctionRecord($user_id, $type, $page, $limit, $roomId);
        return $res;
    }

    //验证用户是否含有特殊权限
    public function getMenu($user_id, $roomId) {
        //房间是否是cbd认证公会
        $isanchor = 0;
        $res = $this->model_union_user->userToUnion($user_id);
        if(!empty($res)){
            //查看公会是否认证
            $checkStatus = $this->model_union->getUnions([$res['un_id']]);
            if(isset($checkStatus[0]['authentication_status']) && $checkStatus[0]['authentication_status'] != 0){
                $isanchor = 1;
            }
        }
        //查看用户是否是公会管理员角色
        $roleId = $this->roomModel->get_role($roomId, $user_id);

        if(!in_array($roleId,[1,2]) || $isanchor != 1){
            return ['menu_permission'=>0];
        }
        return ['menu_permission'=>1];
    }

    //获取费率
    public function getRate(){
        $data = $this->equipModel->getRate();
        return $data;
    }

    //获取用户是否被公聊禁言
    public function isForbidden($user_id){
        $is_forbidden = 0;
        if(!empty(Redis::get($this->auctionChatForbiddenKey.$user_id)) || !empty(Redis::SISMEMBER($this->auctionChatNeverKey,$user_id))){
            $is_forbidden = 1;
        }
        return ['is_forbidden'=>$is_forbidden];
    }

    //举报用户
    public function add_report($user_id, $report_type, $pics, $describe, $sendMsg, $report_userId){
        do{
            $code = Hint::SUCCESS;
            $msg = 'ok';
            DB::beginTransaction();
            try{
                //入库
                $param = [
                    'user_id' => $user_id, //发起举报用户id
                    'report_type' => $report_type, //举报类型
                    'pic' => $pics, //图片
                    'desc' => $describe, //描述
                    'sendMsg' => $sendMsg, //举报文案消息
                    'report_userid'=> $report_userId, //被举报人id
                    'status' => 0,//0未处理1=已处理 2=已封禁
                    'created_at' => Carbon::now()->toDateTimeString()
                ];
                $this->equipModel->insertReport($param);
                DB::commit();
            }catch (\Exception $e) {
                DB::rollBack();
                write_log('error_equipAuctionChatReport', 'INFO 举报失败', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            }
        }while(false);
        return compact('code','msg');
    }
}